<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Admin\Model\AuthGroupModel;
use Think\Page;

/**
 * 后台内容控制器
 * @author huajie <banhuajie@163.com>
 */
class PageController extends AdminController {

    /**
     * 显示左边菜单，进行权限控制
     * @author huajie <banhuajie@163.com>
     */
    protected function getMenu(){
        $map = array(
            'status'  => '1',
        );
        $map['extend'] = array('NEQ','0');
        $model = M('Model')->where($map)->select();

        $this->assign('nodes',      $model);
        $this->assign('show_recycle', IS_ROOT || $this->checkRule('Admin/article/recycle'));
        //获取草稿箱权限
        $this->assign('show_draftbox', C('OPEN_DRAFTBOX'));
        //获取审核列表权限
        $this->assign('show_examine', IS_ROOT || $this->checkRule('Admin/article/examine'));
    }

    /**
     * 分类文档列表页
     * @param integer $cate_id 分类id
     * @param integer $model_id 模型id
     * @param integer $position 推荐标志
     * @param integer $group_id 分组id
     */
    public function index($cate_id = null, $model_id = null, $position = null,$group_id=null){
        //获取左边菜单
        $this->getMenu();

        // 获取基础模型信息
        $model = M('Model')->where(array('id'=>$model_id,'extend'=>'2'))->find();
        $this->assign('model', $model);

        //解析列表规则
        $fields =   array();
        $grids  =   preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }

        $map['status'] = array('EGT',0);
        $count = D($model['name'])->where($map)->count();

        $fields[] = 'model_id';
        // 过滤重复字段信息
        $fields =   array_unique($fields);

        $limit = '';
        $list = D($model['name'])->field($fields)->where($map)->limit($limit)->select();
        // 列表显示处理
        $list   =   $this->parseDocumentList($list,$model['id']);

        $data = array(
            'list' => $list,
            '_total' => $count,
            'list_grids' => $grids,
        );
        $this->assign($data);
        $this->display();
    }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model='Page'){
        return parent::setStatus('Page');
    }

    /**
     * 文档新增页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function add(){
        //获取左边菜单
        $this->getMenu();

        $model_id   =   I('get.model_id',0);
        $info['model_id']       =   $model_id;

        // 获取当前的模型信息
        $model    =   get_document_model($model_id);

        //获取表单字段排序
        $fields = get_model_attribute($model_id);
        $this->assign('info',       $info);
        $this->assign('fields',     $fields);
        $this->assign('type_list',  get_type_bycate($cate_id));
        $this->assign('model',      $model);
        $this->meta_title = '新增'.$model['title'];
        $this->display();
    }

    /**
     * 文档编辑页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function edit(){
        //获取左边菜单
        $this->getMenu();
        $model_id   =   I('get.model_id',0);

        $id     =   I('get.id','');
        if(empty($id)){
            $this->error('参数不能为空！');
        }

        $model = M('Model')->where(array('id'=>$model_id,'extend'=>'2'))->find();

        // 获取详细数据 
        $Page = D($model['name']);
        $data = $Page->find($id);
        if(!$data){
            $this->error($Page->getError());
        }

        // 获取当前的模型信息
        $model    =   get_document_model($model_id);

        //获取表单字段排序
        $fields = get_model_attribute($model_id);

        $this->assign('fields',     $fields);
        $this->assign('data', $data);
        $this->assign('model_id', $model_id);
        $this->assign('model',      $model);

        $this->meta_title   =   '编辑文档';
        $this->display();
    }

    /**
     * 更新一条数据
     * @author huajie <banhuajie@163.com>
     */
    public function update(){
        $id = I('post.id','trim,intval');
        $model_id = I('post.model_id','intval');

        $model = M('Model')->where(array('id'=>$model_id,'extend'=>'2'))->find();

        $mod   =   D($model['name']);
        $data = $mod->create();
        if ($data) {
            if ($id) {
                $res = $mod->save();
            }else{
                $res = $mod->add();
            }
        
            if(!$res){
                $this->error($mod->getError());
            }else{
                $this->success($id?'更新成功':'新增成功', U('Page/index',array('model_id'=>$model_id)));
            }
            
        }else{
            $this->error("失败！");
        }
    }

    /**
     * 待审核列表
     */
    public function examine(){
        //获取左边菜单
        $this->getMenu();

        $map['status']  =   2;
        if ( !IS_ROOT ) {
            $cate_auth  =   AuthGroupModel::getAuthCategories(UID);
            if($cate_auth){
                $map['category_id']    =   array('IN',$cate_auth);
            }else{
                $map['category_id']    =   -1;
            }
        }
        $list = $this->lists(M('Document'),$map,'update_time desc');
        //处理列表数据
        if(is_array($list)){
            foreach ($list as $k=>&$v){
                $v['username']      =   get_nickname($v['uid']);
            }
        }

        $this->assign('list', $list);
        $this->meta_title       =   '待审核';
        $this->display();
    }
}